package alfred.mdp.tsp.dispatcher;

import alfred.mdp.client.Client;
import alfred.mdp.tsp.Titanic;
import alfred.mdp.tsp.storage.TspStorage;
import org.zeromq.ZContext;
import org.zeromq.ZDispatcher;
import org.zeromq.ZFrame;
import org.zeromq.ZMsg;

import java.util.concurrent.TimeUnit;

import static alfred.mdp.messages.ProtocolMessage.get;
import static alfred.mdp.messages.ProtocolMessage.getSubMsg;
import static alfred.mdp.utils.Utils.asString;

/**
 */
public class RequestDispatcher implements Runnable {
    private final TspStorage<ZFrame, ZMsg> storage;
    private final Client client;

    public RequestDispatcher(TspStorage<ZFrame, ZMsg> storage, ZContext context, ZDispatcher dispatcher, String clientsEndpoint) {
        this.storage = storage;
        this.client = new Client(context, dispatcher, clientsEndpoint);
    }

    @Override
    public void run() {

        while (!Thread.currentThread().isInterrupted()) {
            try {
                ZMsg pendingRequest = storage.findPendingRequest();
                if (pendingRequest != null) {
                    ZFrame key = get(pendingRequest, 0);
                    ZMsg originalRequest = getSubMsg(pendingRequest, 3);
                    String forwardingService = asString(get(pendingRequest, 2).getData());
                    ZMsg response = client.request(forwardingService, originalRequest, TimeUnit.SECONDS, 5);

                    ZMsg toStore = new ZMsg();
                    toStore.addLast(Titanic.ResponseCode.OK);
                    toStore.addAll(response);
                    storage.put(key, toStore);
                } else {
                    try {
                        Thread.sleep(200);

                    } catch (InterruptedException e) {
                        Thread.interrupted();

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
